package com.bosssoft.springboot.demo1.controller;

import com.bosssoft.springboot.demo1.service.UserService;
import com.bosssoft.springboot.demo1.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;

/**
 * @desccription 登录逻辑控制器
 * @author ChenTong
 * @date 2020-6-10
 */
@Validated
@Controller
public class LoginController implements WebMvcConfigurer {
    private static final String LOGIN = "login";
    @Autowired
    UserService userService;


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/main").setViewName("main");
    }

    @RequestMapping("/")
    public String showForm(UserVO userVO){
        return LOGIN;
    }

    /**
     * @description 用户登录，在登录前验证User参数是否正确，验证结果通过bindingResult来得知
     * @param user 表单传递数据
     * @param bindingResult 前端检验结果
     * @param session session存放用户数据
     * @return 登录成功返回主界面main/登录失败login
     */
    @PostMapping("/")
    public String checkPersonInfo(@Valid UserVO user, BindingResult bindingResult, HttpSession session){
        if (bindingResult.hasErrors()){
            return LOGIN;
        }
        if (userService.login(user.getName(),String.valueOf(user.getPassword()))){
            session.setAttribute("USER_SESSION",user.getName());
            return "redirect:/main";
        }else {
            return LOGIN;
        }

    }
}
